import React, { useEffect, useState } from "react";
import { Modal, List, Button, Space, Radio, Tag, message } from "antd";
import type { RadioChangeEvent } from 'antd';
import { useRequest } from "ahooks";
import { PlusOutlined } from "@ant-design/icons";
import { addressTypes, modalPropsType } from "@/constants/types";
import { fetchUserPickupAddressList, userPickupAddressAdd, userPickupAddressUpdate, userPickupAddressDelete, userPickupAddressSetDefault } from "../../services";
import AddressUpdate from "../AddressUpdate";


const AddressManage = ({visible, onCancel, onSubmit, currentRow, title}: modalPropsType) => {
  const [data, setData] = useState<addressTypes []>([]);
  const [selected, setSelected] = useState(null);

  // edit address
  const [updateVisible, setUpdateVisible] = useState(false);
  const [selectedRow, setSelectedRow] = useState<addressTypes | null>(null);
  const {loading: updateLoading, runAsync: updateApi} = useRequest(userPickupAddressUpdate, {manual: true});
  const {loading: addLoading, runAsync: addApi} = useRequest(userPickupAddressAdd, {manual: true});

  const search = () => {
    fetchUserPickupAddressList({
      userId: currentRow?.userId
    }).then(
      res => {
        setData(res || []);
      }
    )
  }



  // edit
  const addressUpdateProps = {
    loading: updateLoading|| addLoading,
    visible: updateVisible,
    currentRow: selectedRow,
    title: selectedRow ? '编辑地址' : '新增地址',
    onCancel: () => {
      setUpdateVisible(false);
      setSelectedRow(null);
    },
    onSubmit: async (params: addressTypes) => {
      const apiFunc = selectedRow ? updateApi : addApi;
      const res = await apiFunc({...params, userId: currentRow?.userId});
      if (res?.code === '0') {
        addressUpdateProps.onCancel();
        search();
      }
    }
  }
  const onChange = (e: RadioChangeEvent) => {
    console.log('radio checked', e.target.value);
    setSelected(e.target.value);
  };
  const handleSubmit = () => {
    if (!selected) {
      message.warning('请选择地址');
      return;
    }
    const address = data.find(v => v.id === selected);
    onSubmit(address);
  }


  // delete
  const handleDelete = (record: addressTypes) => {
    Modal.confirm({
      title: '温馨提示',
      content: '是否确定要删除此地址？',
      onOk: () => {
        userPickupAddressDelete({id: record?.id}).then(
          res => {
            if (res?.code === '0') {
              search();
            }
          }
        )
      }
    });
  }
  // set default
  const handleSetDefault = (record: addressTypes) => {
    userPickupAddressSetDefault({id: record?.id}).then(
      res => {
        if (res?.code === '0') {
          search();
        }
      }
    )
  }
  // edit
  const handleEdit = (record: addressTypes) => {
    setSelectedRow(record);
    setUpdateVisible(true);
  }
  // add
  const handleAdd = () => {
    setUpdateVisible(true);
  }

  useEffect(() => {
    if (currentRow?.userId) {
      search();
    } else {
      setData([]);
    }
  }, [currentRow?.userId])

  return (
    <>
      <Modal
        width="1000px"
        title={title}
        open={visible}
        onCancel={onCancel}
        onOk={handleSubmit}
      >
        <Radio.Group onChange={onChange} value={selected} style={{width: '100%'}}>
          <List
            itemLayout="horizontal"
            dataSource={data}
            renderItem={(item) => (
              <List.Item
                actions={String(item.isDefault) === '1' ? [
                  [
                    <Button key="edit" type="link" onClick={() => handleEdit(item)}>编辑</Button>,
                    <Button key="delete" type="link" onClick={() => handleDelete(item)}>删除</Button>
                  ]
                ] : 
                [
                  <Button key="set-default" type="link" onClick={() => handleSetDefault(item)}>设为默认</Button>,
                  <Button key="edit" type="link" onClick={() => handleEdit(item)}>编辑</Button>,
                  <Button key="delete" type="link" onClick={() => handleDelete(item)}>删除</Button>
                ]
              }
              >
                <List.Item.Meta
                  key={item.id}
                  avatar={<Radio value={item.id} />}
                  title={<Space><strong>{item.contacts}</strong> <strong>{item.mobile}</strong>{String(item.isDefault) === '1' && <Tag color="#f50">默认地址</Tag>}</Space>}
                  description={[item.province, item.city, item.area, item.address].filter(v => !!v).join('')}
                />
              </List.Item>
            )}
          />
        </Radio.Group>
        <div style={{marginTop: 20, paddingLeft: '40px'}}>
          <Button type="primary" onClick={handleAdd} icon={<PlusOutlined />}>新增地址</Button>
        </div>
      </Modal>
      {updateVisible && <AddressUpdate {...addressUpdateProps} />}
    </>
  );
}
export default AddressManage;